package com.brillilab.service.logic.account;

import com.brillilab.domain.enums.account.ExchangeStateEnum;
import com.brillilab.domain.po.account.ExchangeRecord;
import com.brillilab.domain.vo.user.UserInfoVo;
import com.brillilab.service.core.account.IExchangeRecordService;
import com.brillilab.service.core.account.IntegralRecordService;
import com.brillilab.service.core.account.UserAccountService;
import com.brillilab.service.utils.CheckSumUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author linzhikang
 * @description
 * @date 2019-10-15 18:02
 */
@Service
@Transactional
public class ExchangeRecordLogic {

    @Resource
    private IExchangeRecordService exchangeRecordService;

    @Resource
    private IntegralRecordService integralRecordService;

    @Resource
    private UserAccountService userAccountService;

    /**
     * @Description: 积分兑换
     * @Param [userId, labId]
     */
    public String withdraw(UserInfoVo userInfoVo) {
        Long userId = userInfoVo.getId();
        Long labId = userInfoVo.getLabId();
        //获取可兑换账户积分
        int amount = userAccountService.exchangeIntegral(userId);
        Assert.isTrue(amount != 0, "无可提现积分！");
        //添加兑换记录
        ExchangeRecord exchangeRecord = new ExchangeRecord();
        exchangeRecord.setUserId(userId);
        exchangeRecord.setUserName(userInfoVo.getName());
        exchangeRecord.setMobile(userInfoVo.getMobile());
        exchangeRecord.setLabId(labId);
        exchangeRecord.setLabName(userInfoVo.getLabName());
        exchangeRecord.setAmount(amount);
        //md5(userId + labId + 时间)
        String code = userId + "" + labId + new Date().getTime();
        String encryCode = CheckSumUtil.getMD5(code).toUpperCase();
        exchangeRecord.setCode(encryCode);
        exchangeRecordService.insert(exchangeRecord);
        //更新积分记录状态
        integralRecordService.exchangeIntegral(userId, exchangeRecord.getId());
        return encryCode;
    }
}
